//
// Created by hjie on 23-7-23.
//

#include "aac_parser.h"
#include <sys/file.h>

AACParser::AACParser(const std::string &filename)
{
    m_parse_filename = filename;
    m_buffer = nullptr;
}

AACParser::~AACParser()
{
    if (m_buffer)
    {
        delete m_buffer;
    }
}

bool AACParser::OpenFile()
{
    auto index = m_parse_filename.find_last_of('.');
    if (index == std::string::npos)
    {
        return false;
    }
    if (m_parse_filename.substr(index+1).compare("aac") != 0)
    {
        return false;
    }
    int fp = open(m_parse_filename.c_str(), O_RDONLY, 0666);
    if (fp < 0)
    {
        return false;
    }
    m_buffer = new DataBuffer(fp);
    int state = 0;
    int size = m_buffer->ReadData(state);
    if (state < 0)
    {
        return false;
    }
    else
    {
        printf("buffer size : %d.\n", size);
    }
    return true;
}

bool AACParser::ParseData()
{
    size_t read_size = m_buffer->Length();
    uint8_t * buffer = m_buffer->Data();
    int index = 0;
    do
    {
        AACFrame frame;
        if (frame.AdtsFixedHeader(buffer, read_size, index))
        {
            buffer = buffer + index;
            read_size = read_size - index;
            frame.AdtsVariableHeader(buffer, read_size, index);

            buffer = buffer + index;
            read_size = read_size - index;
            m_frame_vec.push_back(frame);
            m_buffer->RemoveData(frame.m_aac_frame_length);
        }
        else
        {
            int state = 0;
            m_buffer->ReadData(state);
            if (state < 0)
            {
                break;
            }
            else
            {
                buffer    = m_buffer->Data();
                read_size = m_buffer->Length();
            }
        }
    }while(read_size >= 7);

    for (auto & data : m_frame_vec)
    {
        data.DumpFixedHeader();
        data.DumpVariableHeader();
    }
    printf("frame count : %ld.\n", m_frame_vec.size());
    return true;
}

void AACParser::DumpFrameData(const std::string &dump_filename)
{

}



